package pers.crayon.baseprogram.util;


import lombok.experimental.UtilityClass;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;


/**
 * 切面工具类
 */
@UtilityClass
public class AspectUtil {

    /**
     * 获取切面方法注解
     *
     * @param joinPoint
     * @param annotationClass
     * @return
     * @throws NoSuchMethodException
     */
    public Annotation getAnnotation(JoinPoint joinPoint, Class<? extends Annotation> annotationClass) throws NoSuchMethodException {
        Signature signature = joinPoint.getSignature();
        //类
        Class<? extends MethodInvocationProceedingJoinPoint> declaringType = signature.getDeclaringType();
        Class<?>[] parameterTypes = ((MethodSignature) signature).getMethod().getParameterTypes();
        //方法
        Method method = declaringType.getMethod(signature.getName(), parameterTypes);
        if (method.isAnnotationPresent(annotationClass)) {
            return method.getAnnotation(annotationClass);
        }
        return null;
    }
}